
// jms: Maybe we can remove this?
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "swagme.h"
#include "Player.h"
#include "Scene.h"
#include "Display.h"
#include "Game.h"
#include <ctime>

const char* swVersion = "Run #7";

// modified from http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials/gfxsdl/tut1

int main(int argc, char *argv[])
{
  printf("In dir (%s)\n", argv[0]);

  srand((unsigned int)time(NULL));

  cout <<"Initializing SDL." << endl;
  if ( SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO) < 0 ) {
    printf("Unable to init SDL: %s\n", SDL_GetError());
    exit(1);
  } else {
    cout << "Initialized SDL correctly" << endl;
  }

  if(Mix_OpenAudio(44100, AUDIO_S16, 1, 4096)) {
    cout << "Unable to open audio: " << Mix_GetError() << endl;
    exit(2011);
  }
  cout << "Opened audio" << endl;

  atexit(quit);

  char swTitle[200];
  sprintf(swTitle, "Swag Me (%s)", swVersion);
  SDL_WM_SetCaption(swTitle, "Swag Me");

  // initialize the game and the Display (my plan is to eventually move Scene,
  // Player, Sprite instances into the Game and Display objects)
  Game* theGame = new Game();

  int done=0;
  Uint32 prevTick = SDL_GetTicks();
  Uint32 thisTick = SDL_GetTicks();
  while(done == 0)
  {
    // handle events
    Uint8 *keystate;
    SDL_Event event;
    while ( SDL_PollEvent(&event) )
    {
      switch (event.type) {
        case SDL_QUIT:
          done = 1;
          break;
        case SDL_KEYDOWN:
          switch (event.key.keysym.sym) {
            case SDLK_ESCAPE: // fallthrough
            case SDLK_RETURN:
            case SDLK_q:
              done = 1;
              break;
            case SDLK_r:
			        cout << "'R' pressed, resetting game:" << endl;
              if(theGame) { delete theGame; }
              cout << "Game destroyed" << endl;
              theGame = new Game();
              break;
            case SDLK_m:
              cout << "<<<<<<<<<<<<<<<<<<<<<< MARK >>>>>>>>>>>>>>>>>>>>>>" << endl;
              theGame->dumpColMap();
              break;
            default:
              break;
          }
          break;
        default:
          break;
      }
    }
    keystate = SDL_GetKeyState(NULL);

    // update Game and Status area (eventually my plan is to migrate 
    // more stuff into this and the Display objects)
	  prevTick = thisTick;
	  thisTick = SDL_GetTicks();
    theGame->update(keystate, prevTick, thisTick);
  } // while(done == 0)

  delete theGame;

  return 0;
}

// TO DO: make sure this includes all values in the proper range - I think there is a rare bug here
// returns a random number in the inclusive range (min, max)
int random(int min, int max) {
  int range = max - min + 1;
  return (int)( range * (double)rand()/RAND_MAX ) + min;
}

void quit() {
  Mix_CloseAudio();
  SDL_Quit();
}
